import { ComponentClass } from 'react'
import Taro, { Component } from '@tarojs/taro'
import { View, Text, Image, Button } from '@tarojs/components'

import ProductType from '../../model/product'
import Apply from '../../model/apply'
import { default as Product } from '../../utils/product'
import { User as UserUtils } from '../../utils/user'
import Constants from '../../config/constants'

import ProductTag from '../product-tag'
import checkboxActive from '../../asset/images/product-list-item/checkbox-active.png'
import checkboxDefault from '../../asset/images/product-list-item/checkbox-default.png'

import './index.scss'

type PageStateProps = {}

type PageDispatchProps = {}

type PageOwnProps = {
  // 要显示的产品
  product: ProductType,
  // 是否要显示勾选框
  isShowCheck: boolean,
  // 是否要显示放款时间
  isShowLoanTime: boolean,
  // 是否要显示申请按钮
  isShowApply: boolean,
  // 是否要显示取消收藏
  isShowCollectCancel: boolean,
  // 当前用户已申请的产品订单列表
  userApplyList: Apply[],
}

type PageState = {
  // 当前产品是否已申请过
  isApply: boolean,
  // 当前产品是否被选中, 作为匹配产品显示时, 可以被选中
  isCheck: boolean,
  // 产品类型tag
  productTypeTagStyle: any,
  // 易通过tag
  easyTagStyle: any,
}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface ProductListItem {
  props: IProps;
  state: PageState;
}

const productUtil = new Product()
const userUtils = new UserUtils()

/**
 * 产品过滤组件
 */
class ProductListItem extends Component {

  constructor(props) {
    super(props);

    this.state = {
      isApply: false,
      isCheck: false,
      productTypeTagStyle: {
        border: '1px solid #23aab6',
        color: '#23aab6',
        backgroundColor: '#fff',
        fontSize: '10px',
        lineHeight: '1.2',
      },
      easyTagStyle: {
        border: '1px solid #f9a347',
        color: '#f9a347',
        backgroundColor: '#fff',
        fontSize: '10px',
        lineHeight: '1.2',
      },
    }
  }

  componentWillReceiveProps(nextProps) {

    // 用户订单有变化的情况下，计算产品的已申请状态
    const curApplyList = this.props.userApplyList
    const nextApplyList = nextProps.userApplyList
    if (JSON.stringify(curApplyList) !== JSON.stringify(nextApplyList)) {
      this.setIsApply()
    }
  }

  componentWillMount() {
    // 计算产品的已申请状态
    this.setIsApply()
  }

  componentWillUnmount() {

  }

  componentDidShow() { }

  componentDidHide() { }

  render() {
    // const inputOption = this._getInputOptionWithDefaultValue(this.props)
    return (
      <View className="product-list-item-container" onClick={this.onViewTap}>
        <View className="row">
          {/*  产品名, logo */}
          <View className="name-box">
            <View className="left">
              <Image className="logo" src={this.props.product.logo}></Image>
              <Text className="name">{this.props.product.title}</Text>
            </View>

            <View className="right">
              {this.props.product.apply_count >= 10
                && this.props.product.apply_count < 1000
                && <Text className="description">已有{this.props.product.apply_count}人申请</Text>
              }
              {this.props.product.apply_count >= 1000 && <Text className="description">已有1000+人申请</Text>}
            </View>
          </View>
          <View className="content-box">
            {this.props.isShowCheck && <View className="column column-center" data-productid={this.props.product.product_id}>
              <View className="check-radio">
                <Image className="image" src={this.state.isCheck ? checkboxActive : checkboxDefault}></Image>
              </View>
            </View>}

            <View className="column">
              {/* 额度范围 */}
              <Text className="limit red">{productUtil.convertDepositRangeToDisplayStr(this.props.product.min_deposit, this.props.product.max_deposit)}</Text>
              <Text className="description">额度范围(元)</Text>
            </View>
            <View className="column">
              <View className="column-row">
                <Text className="description">月利率&nbsp;</Text>
                <Text className="red number">{productUtil.converCombinationRateTypeToDisplayStr(this.props.product.combination_rate_type, this.props.product.combination_rate)}</Text>
              </View>
              <Text className="description">期限 {this.props.product.min_time_limit}-{this.props.product.max_time_limit}个月</Text>
              {this.props.isShowLoanTime && <Text className="description">{productUtil.converLoanTimeToDisplayStr(this.props.product.loan_time, this.props.product.loan_time_type)}</Text>}
            </View>
            {this.props.isShowApply && <View className="column">
              <Button className={`apply-button  ${this.state.isApply ? 'is-apply' : ''}`} onClick={process.env.TARO_ENV === 'weapp' ? this.onProductButtonClick : this.onProductButtonClick.bind(this)}>
                <Text className="text">{this.state.isApply ? '已申请' : '立即申请'}</Text>
              </Button>
            </View>}

          </View>
        </View>

        {/* 底部行 */}
        {(this.props.isShowCollectCancel
          || this.props.product.product_type
          || this.props.product.easy_pass === 1)
          && <View className="tag-row">
            <View className="direction-row-column">
              {this.props.product.product_type
                && <ProductTag text={productUtil.convertProductTypeToString(this.props.product.product_type)} styleClass={this.state.productTypeTagStyle} />}

              {this.props.product.easy_pass === 1 &&
                <ProductTag text="易通过" styleClass={this.state.easyTagStyle} />}

            </View>
            {this.props.isShowCollectCancel
              && <View className="direction-row-column" onClick={process.env.TARO_ENV === 'weapp' ? this.onProductCollectCancel : this.onProductCollectCancel.bind(this)}>
                <View className="collect-cancel">
                  <Text className="iconfont icon-shoucang collect-icon" />
                  <Text className="text">取消收藏</Text>
                </View>
              </View>}
          </View>}

      </View >)
  }

  /**
   * 立即申请处理方法
   * @param e 
   */
  onProductButtonClick(e) {
    // console.log('onProductButtonClick product = ', this.props.product.product_id)
    this._productApply(this.props.product)
  }

  /**
   * 产品申请处理方法, 根据不同产品类型跳转
   */
  _productApply(product) {

    if (!product) {
      Taro.showToast({
        title: '抱歉，该产品不存在',
        icon: 'none'
      })
      return
    }

    const {
      product_id,
      product_type
    } = product

    // 默跳转到快速贷
    let url = `/pages/fastProductApply/index?product_id=${product_id}`

    if (product_type) {
      // 有 product_type 字段是银行贷
      url = `/pages/bankProductDetail/index?product_id=${product_id}`
    }

    // 检查是否已登录，未登录则跳转到登录页
    if (!userUtils.isLoginValid) {
      userUtils.checkIsLogin(encodeURIComponent(url))
    } else {
      Taro.navigateTo({
        url
      })
    }
  }

  /**
   * 取消收藏处理方法
   */
  onProductCollectCancel() {
    Taro.eventCenter.trigger(`${Constants.PRODUCT_CANCLE_COLLECT_EVENT}`, {
      product_id: this.props.product.product_id,
      collection_id: this.props.product.collection_id,
    })
  }

  /**
   * 产品子列表组件点击的处理方法 
   * @param {*} event 
   */
  onViewTap = (event) => {
    // 有勾选功能的情况下，点击组件也发射组件选择事件
    if (this.props.isShowCheck) {
      this.onCheckTap()
    }
  }

  /**
   * 产品勾选改变的处理方法
   */
  onCheckTap = () => {
    const { product } = this.props
    let isCheck = this.state.isCheck

    // 改变选中状态
    this.setState({
      isCheck: !isCheck,
    })

    // 发射选中事件
    Taro.eventCenter.trigger(Constants.PRODUCT_LIST_ITEM_CHECK_EVENT, {
      checked: !isCheck,
      product: product
    }, {})
  }

  /**
   * 检查产品是否已申请
   */
  setIsApply() {
    // 检查产品是否已申请
    const isApply = productUtil.checkIsApplyProduct(this.props.product)
    this.setState({
      isApply,
    })
  }

}

export default ProductListItem as ComponentClass<PageOwnProps, PageState>

